#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
from django.db import models
from django.conf import settings
import os, Image


TINY_SIZE = (80,80)    #thumb size (x,y)


class PhotoPost(models.Model):
   post_date = models.DateTimeField(null=False)
   pub_date = models.DateTimeField(null=False)
   title = models.CharField(blank=True, null=True, maxlength=100)
   text = models.TextField(blank=True, null=True)
   photo = models.ImageField(blank=True, null=True, upload_to=settings.PHOTOPOST_FOLDER+'%Y-%m-%d')

   def create_thumbnail(self):
      pass

   def admin_thumb(self):
      try:
         thumb = self.photo.replace('\\','/').split('/')
         thumb[-1] = settings.THUMBNAILS_SUBFOLDER + thumb[-1]
         thumb = '/'.join(thumb)    #THUMBNAIL_SUBFOLDER + name.ext
         datesubfolder = self.post_date.strftime('%Y-%m-%d')
         
         # on verifie que le dossier thumbnails existe, sinon on le crée
         if not os.path.exists(settings.PHOTOPOST_FOLDER + datesubfolder +'/'+settings.THUMBNAILS_SUBFOLDER):
            os.mkdir(settings.PHOTOPOST_FOLDER + datesubfolder +'/'+settings.THUMBNAILS_SUBFOLDER)
         
         # on verifie que le thumbnail existe, sinon on le crée
         if not os.path.exists(settings.PHOTOPOST_FOLDER + datesubfolder +'/'+settings.THUMBNAILS_SUBFOLDER + self.photo.split('/')[-1]):
            im = Image.open(self.photo)
            im.thumbnail(TINY_SIZE, Image.ANTIALIAS)
            im.save(thumb, "JPEG")
         #return settings.PHOTOPOST_FOLDER + self.post_date.strftime('%Y-%m-%d')+'<br>'+thumb
         return """<a href="%s%s/%s"><img src="%s%s/%s%s" alt="" /></a>""" % (settings.HTTP_PATH_TO_PHOTOS, datesubfolder, self.photo.split('/')[-1],  settings.HTTP_PATH_TO_PHOTOS, datesubfolder, settings.THUMBNAILS_SUBFOLDER, self.photo.split('/')[-1])
         
      except Exception, err:
         return err
   admin_thumb.allow_tags = True

   class Admin:
      list_display = ('post_date', 'title', 'admin_thumb')  
   class Meta:
      pass
    